package com.wyp.design.pattern.creational.prototype.v3;

import com.wyp.design.pattern.creational.singleton.hungry.HungrySingleton;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * debug发现克隆出新对象中Date属性 和原始对象为一个引用。所以需要修改clone方法，让其Date类型也进行clone，或者使用序列化和反序列化操作。
 * 实现Cloneable接口证明才可能被克隆，要被克隆还需要重写clone方法
 * 当修改date时发现克隆对象的date也被修改。浅拷贝
 *
 * @author: Oliver
 * @time: 2020/5/8/22:40
 */
public class Test {
    public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Date birthday = new Date(0L);
        Pet pig1 = new Pet("狗", birthday);
        Pet pig2 = (Pet) pig1.clone();
        System.out.println(pig1);
        System.out.println(pig2);

        pig1.getBirthday().setTime(666666666666L);

        System.out.println(pig1);
        System.out.println(pig2);

        // 克隆对单例的破坏。
        HungrySingleton instance = HungrySingleton.getInstance();
        Class<HungrySingleton> singletonClass = HungrySingleton.class;
        Method clone = singletonClass.getDeclaredMethod("clone");
        clone.setAccessible(true);
        HungrySingleton invoke = (HungrySingleton) clone.invoke(instance);
        System.out.println(invoke);
        System.out.println(instance);
    }
}
